package com.kaifamiao.tcp;
import java.io.*;
import java.net.*;
import java.util.*;

public class FolderClient {
    private static final String SERVER_ADDRESS = "127.0.0.1";
    private static final int SERVER_PORT = 12345;
    private static final String SOURCE_PATH = "/Users/linrui/a/";

    public static void main(String[] args) {
        List<File> filesToSend = getFiles(SOURCE_PATH);
        try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT)) {
            System.out.println("Connected to server.");

            sendFiles(socket, filesToSend);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendFiles(Socket socket, List<File> filesToSend) throws IOException {
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeInt(filesToSend.size());

        for (File file : filesToSend) {
            String relativePath = file.getAbsolutePath().substring(SOURCE_PATH.length());
            dos.writeUTF(relativePath);
            dos.writeLong(file.length());

            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    dos.write(buffer, 0, bytesRead);
                }
            }
            System.out.println("Sent: " + relativePath);
        }
    }

    private static List<File> getFiles(String directory) {
        List<File> filesList = new ArrayList<>();
        File dir = new File(directory);
        if (dir.exists()) {
            getFilesRecursively(dir, filesList);
        }
        return filesList;
    }

    private static void getFilesRecursively(File dir, List<File> fileList) {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                getFilesRecursively(file, fileList);
            } else {
                fileList.add(file);
            }
        }
    }
}
